﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Speech.Recognition;

namespace ms_Recognition
{
    public partial class ms_Recognition : Form
    {
        public ms_Recognition()
        {
            InitializeComponent();
        }

        private SpeechRecognitionEngine Recognizer = new SpeechRecognitionEngine();
        private void ms_Recognition_Load(object sender, EventArgs e)
        {
            try
            {
                Recognizer.SetInputToDefaultAudioDevice();
            }
            catch (Exception err)
            {
                MessageBox.Show("请插入麦克风后再启动程序。\n系统提示：" + err.Message, "MS Recognition", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //MessageBox.Show(err.Message, "MS Recognition", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Application.Exit();
            }
            Recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(Recognizer_SpeechRecognized);
        }

        void Recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            tBox_RgnText.AppendText(e.Result.Text + " ");
        }

        private void btn_Rgn_Click(object sender, EventArgs e)
        {
            //当前是识别中，点击按键后停止识别
            if ((btn_Rgn.Tag as string) == "stopRgn")
            {
                Recognizer.RecognizeAsyncCancel();//直接取消当前识别，丢弃未完成结果。不会有RecognizeComplete()事件
                //Recognizer.RecognizeAsyncStop();//完成当前识别后停止，停止成功会发出RecognizeComplete()事件
                btn_Rgn.Text = "识别";
                btn_Rgn.Tag = "startRgn";
                return;
            }

            //当前停止状态，开始识别，先看关键词组是否已经预备好。
            if (tBox_OrgText.Text.Length == 0)
            {
                MessageBox.Show("请输入关键词组，用回车分开。", "MS Recognition", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            //建立词库
            GrammarBuilder gb;
            char[] splitChars = { ' ', ',', '.', '!', '?' };
            if (tBox_OrgText.Lines.Length == 1)//只有一行时按空格分单词
            {
                gb = new GrammarBuilder(new Choices(tBox_OrgText.Text.ToLower().Split(splitChars)));
            }
            else//多行时，按每行一个词组识别
            {
                gb = new GrammarBuilder(new Choices(tBox_OrgText.Lines));
            }
            Recognizer.UnloadAllGrammars();
            Recognizer.LoadGrammar(new Grammar(gb));

            //界面处理，开始识别
            tBox_RgnText.Clear();
            btn_Rgn.Text = "停止";
            btn_Rgn.Tag = "stopRgn";

            Recognizer.RecognizeAsync(RecognizeMode.Multiple);
        }
    }
}
